package com.jeeplus.modules.sys.service;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.utils.DbUtils;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.ObjectUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.base.ObjectUtil;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.modules.sys.entity.*;
import com.jeeplus.modules.sys.entity.BuyerOrderInfo.BuyerOrderStore;
import com.jeeplus.modules.sys.entity.BuyerOrderInfo.BuyerOrderSum;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.test.one.dialog.entity.Leave1;
import com.jeeplus.modules.tools.utils.MultiDBUtils;
import com.jeeplus.modules.tools.utils.SpringUtil;
import org.apache.ibatis.jdbc.SQL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author Administrator
 * @title: 集单服务
 * @projectName JeePlus
 * @description: TODO
 * @date 2019/9/1613:12
 */
@Service
@Transactional(readOnly = true)
public class OrderCollectionService {
    @Autowired
    DbUtils dbUtils;
    protected JdbcTemplate jdbcTemplateVss = (JdbcTemplate) SpringUtil.getApplicationContext().getBean("db");
    protected Logger logger = LoggerFactory.getLogger(getClass());

    public Page<Leave1> findPage(Page<Leave1> page, Leave1 leaveDialog) {
        NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplateVss);
        Map<String, Object> params = new HashMap<String, Object>();
        String sql = "select guid id,ORD_SEQ," +
                "       CX_ITEM," +
                "       ERP_ITEM," +
                "       ITEM_DESCR," +
                "       SUPPL_NAME," +
                "       SPCI," +
                "       MIN_ORD_QTY," +
                "       UNIT," +
                "       ORD_QTY," +
                "       to_char(CREATE_DATE, 'yyyy-mm-dd') CREATE_DATE " +
                "  from sn_order_imp " +
                " where flag = 1 ";
        //sql="select * from sn_order_imp";
        User currentUser = UserUtils.getUser();
        params.put("UserId",currentUser.getId().toString());
        sql +=" and CREATE_ID = :UserId";
        try {
            page.setCount(jdbcTemplate.queryForObject(dbUtils.getCountString(sql), params, Integer.class));
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        sql = new DbUtils().getLimitString(sql, page.startRow(), page.endRow());
        params.put("rowStart", page.startRow());
        params.put("rowEnd", page.endRow());
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, params);
        page.setListData(list);
        return page;
    }
    public Page<Leave1> BuyerOrderDetail(Page<Leave1> page, Leave1 leaveDialog){
        NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplateVss);
        Map<String, Object> params = new HashMap<String, Object>();
        String sql = "select rownum id,d.* from sn_buyer_order_detail d";
        User currentUser = UserUtils.getUser();
        //params.put("UserId",currentUser.getId().toString());
        //sql +=" and CREATE_ID = :UserId";
        try {
            page.setCount(jdbcTemplate.queryForObject(dbUtils.getCountString(sql), params, Integer.class));
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        sql = new DbUtils().getLimitString(sql, page.startRow(), page.endRow());
        params.put("rowStart", page.startRow());
        params.put("rowEnd", page.endRow());
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, params);
        page.setListData(list);
        return page;
    }
    public List<BuyerOrderDetail> ExpBuyerOrderDetail(){
        try {
            NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplateVss);
            Map<String, Object> params = new HashMap<String, Object>();
            String sql = "select rownum \"Id\",d.cx_item \"CxItem\",d.erp_item \"ErpItem\",d.item_descr \"ItemDescr\",d.spci \"Spci\",d.spci \"Unit\",d.ord_qty \"OrdQty\" from sn_buyer_order_detail d ";
            User currentUser = UserUtils.getUser();
            RowMapper<BuyerOrderDetail> rowMapper=BeanPropertyRowMapper.newInstance(BuyerOrderDetail.class);
            List<BuyerOrderDetail> list = jdbcTemplate.query(sql, params, rowMapper);
            System.out.println(list);
            return list;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return new ArrayList<BuyerOrderDetail>();
    }
    public List<BuyerOrderStore> ExpStoreBuyerOrderDetail(){
        try {
            NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplateVss);
            Map<String, Object> params = new HashMap<String, Object>();
            String sql = "select store \"Store\",name \"StoreName\",cx_item \"CxItem\",spci \"Spci\",ord_qty \"OrdQty\",item_descr \"CxItemDescr\" from sn_st_buyer_order_detail";
            User currentUser = UserUtils.getUser();
            RowMapper<BuyerOrderStore> rowMapper=BeanPropertyRowMapper.newInstance(BuyerOrderStore.class);
            List<BuyerOrderStore> list = jdbcTemplate.query(sql, params, rowMapper);
            System.out.println(list);
            return list;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return new ArrayList<BuyerOrderStore>();
    }
    public List<BuyerOrderSum> ExpSumBuyerOrderDetail(){
        try {
            NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplateVss);
            Map<String, Object> params = new HashMap<String, Object>();
            String sql = "select cx_item \"CxItem\",\n" +
                    "       spci \"Spci\",\n" +
                    "       sum(ord_qty) \"OrdQty\",\n" +
                    "       item_descr \"CxItemDescr\"\n" +
                    "  from sn_st_buyer_order_detail\n" +
                    " group by cx_item, spci, item_descr ";
            User currentUser = UserUtils.getUser();
            RowMapper<BuyerOrderSum> rowMapper=BeanPropertyRowMapper.newInstance(BuyerOrderSum.class);
            List<BuyerOrderSum> list = jdbcTemplate.query(sql, params, rowMapper);
            System.out.println(list);
            return list;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return new ArrayList<BuyerOrderSum>();
    }
    public boolean isNumber(String str) {
       try {
           boolean isInt = Pattern.compile("^-?[1-9]\\d*$").matcher(str).find();
           boolean isDouble = Pattern.compile("^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)$").matcher(str).find();
           return isInt || isDouble;
       }
       catch (Exception e){
           logger.error(e.getMessage());
       }
       return false;
    }
    public ReturnInfo impOrder(Map<String, Object> map,String officeCode,String userId) {
        ReturnInfo returnInfo = new ReturnInfo();
        returnInfo.setResusltCode(0);
        try {
            logger.info(JSONUtils.toJSONString(map));
            StringBuilder sb = new StringBuilder();
            if (map.get("畅想编号") == null) {
                sb.append("畅想编号,");
            }
            if (map.get("ERP编号") == null) {
                sb.append("ERP编号为空,");
            }
            if (map.get("商品名称") == null) {
                sb.append("商品名称为空,");
            }
            if (map.get("供应商") == null) {
                sb.append("供应商为空,");
            }
            if (map.get("规格") == null) {
                sb.append("规格为空,");
            }
            if (map.get("最小订货数量") == null) {
                sb.append("最小订货数量为空,");

            }
            else {
                if(!isNumber(map.get("最小订货数量").toString())){
                    sb.append("最小订货数量非法数值");
                }
            }
            if (map.get("单位") == null) {
                sb.append("单位为空,");
            }
            if (map.get("订货数量") == null) {
                sb.append("订货数量为空,");
            }
            else {
                if(!isNumber(map.get("订货数量").toString())){
                    sb.append("订货数量非法数值");
                }
                else {
                    if(Double.valueOf(map.get("订货数量").toString()) % Double.valueOf(map.get("最小订货数量").toString())!=0){
                        sb.append("订货数量不匹配");
                    }
                }
            }
            if (!StringUtils.isEmpty(sb.toString())) {
                returnInfo.setResusltCode(0);
                returnInfo.setErrorInfo(sb.toString());
                return returnInfo;
            }

            String sql = String.format("insert into sn_order_imp\n" +
                            "  (ORD_SEQ,\n" +
                            "   CX_ITEM,\n" +
                            "   ERP_ITEM,\n" +
                            "   ITEM_DESCR,\n" +
                            "   SUPPL_NAME,\n" +
                            "   SPCI,\n" +
                            "   MIN_ORD_QTY,\n" +
                            "   UNIT,\n" +
                            "   ORD_QTY,\n" +
                            "   CREATE_ID,\n" +
                            "   STORE)\n " +
                            "values('%s','%s','%s','%s','%s','%s','%s','%s',%f,'%s',%f)", map.get("序号"), map.get("畅想编号"), map.get("ERP编号"), map.get("商品名称"), map.get("供应商"), map.get("规格"),
                    map.get("最小订货数量"), map.get("单位"), Double.valueOf(map.get("订货数量").toString()),userId,Double.valueOf(officeCode));
            jdbcTemplateVss.update(sql);
            returnInfo.setResusltCode(1);
            returnInfo.setErrorInfo("");
            return returnInfo;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            returnInfo.setResusltCode(2);
        }
        return returnInfo;
    }
    public ReturnInfo orderCommit(String userId){
        ReturnInfo returnInfo=new ReturnInfo();
        returnInfo.setResusltCode(0);
        try {
            if(userId.isEmpty())
            {
                returnInfo.setErrorInfo("用户ID不能为空!");
                returnInfo.setResusltCode(0);
                return returnInfo;
            }
            if(jdbcTemplateVss.queryForObject(String.format("select count(*) from sn_order_imp where create_id = %s and flag=1",userId),Integer.class)<=0){
                returnInfo.setResusltCode(0);
                returnInfo.setErrorInfo("未检测到数据!");
                return returnInfo;
            }
            String OrderId=jdbcTemplateVss.queryForObject("select SN_ORDER_SEQ.NEXTVAL  from dual",String.class);
            jdbcTemplateVss.update(String.format("call sn_order_commit('%s','%s')",userId,OrderId));
            List<Map<String,Object>> list=jdbcTemplateVss.queryForList(String.format("select p.error_info,p.flag,p.erp_item,p.store,p.ord_seq from sn_order_imp p where id='%s' ",OrderId));
            Integer successNum=0;
            Integer failNum=0;
            StringBuilder sb=new StringBuilder();
            if(list.size()>0)
            {
                for (Map<String,Object> map:list){
                    if(map.get("ERROR_INFO").equals("处理成功")){
                        successNum++;
                    }
                    else {
                        failNum++;
                        sb.append(String.format("导入失败:第【%s】条记录，商品【%s】,错误信息【%s】<br >",map.get("ORD_SEQ"),map.get("ERP_ITEM"),map.get("ERROR_INFO")));
                    }
                }
            }
            String msg="";
            if(successNum>0){
                msg+= String.format("提交成功：共计【%s】记录。<br >",successNum);
            }
            if(failNum>0){
                msg+= String.format("提交失败：共计【%s】记录。<br >",failNum);
            }
            if(!sb.toString().isEmpty())
            {
                msg+=sb.toString();
            }
            returnInfo.setResusltCode(1);
            returnInfo.setErrorInfo(msg);
            return returnInfo;
        }
        catch (Exception e){
            logger.error(e.getMessage());
            returnInfo.setResusltCode(2);
            returnInfo.setErrorInfo("订单提交操作异常!");
        }
        return returnInfo;
    }
    public ReturnInfo delOrderImp(String itemData){
        ReturnInfo returnInfo=new ReturnInfo();
        returnInfo.setResusltCode(0);
        try {
            JSONArray jsonArray=JSONArray.parseArray(itemData);
            List<String> listSql=new ArrayList<>();
            for (int i=0;i<jsonArray.size();i++){
                String ordId= JSONObject.parseObject(jsonArray.getString(i)).getString("id");
                String sql= String.format("update sn_order_imp set flag=-1 where guid='%s'",ordId);
                listSql.add(sql);
            }
            String[] sqlStr=new String[listSql.size()];
            listSql.toArray(sqlStr);
            jdbcTemplateVss.batchUpdate(sqlStr);

            returnInfo.setResusltCode(1);
            returnInfo.setErrorInfo("删除成功!");
        }catch (Exception e){
            logger.error(e.getMessage());
            returnInfo.setResusltCode(2);
            returnInfo.setErrorInfo("导入订单删除失败");
        }
        return returnInfo;
    }
}
